package com.lazypeople.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

public class RegistryUtils {
    private static final Logger logger = LoggerFactory.getLogger(RegistryUtils.class);
    // 要检查的协议列表（与注册时保持一致）
    private static final String[] PROTOCOLS = { "http", "https", "magnet" };
    private static final String APP_NAME = "IdiotDownloader";

    /**
     * 注册多个协议关联
     */
    public static boolean registerSystemProtocols() {
        try {
            // 获取exe路径（需打包工具配置，如Launch4j的-Dexe.path参数）
            String exePath = System.getProperty("exe.path");
            if (exePath == null) {
                // 修正为实际安装路径（请根据实际情况修改）
                exePath = "C:\\Program Files\\IdiotDownloader\\IdiotDownloader.exe";
            }

            // 构建命令行（%1会被替换为点击的URL）
            // 确保路径带引号且%1参数正确传递
            String command = String.format("\"%s\" %%1", exePath);

            // 为每个协议注册
            for (String protocol : PROTOCOLS) {
                String protocolKey = "HKEY_CURRENT_USER\\Software\\Classes\\" + protocol;
                logger.info("开始注册协议: {}，注册表路径: {}", protocol, protocolKey);
                logger.info("使用命令: {}", command);

                // 设置协议处理程序
                executeRegCommand("add", protocolKey, "/ve", "/d", APP_NAME, "/f");
                executeRegCommand("add", protocolKey, "/v", "URL Protocol", "/d", "", "/f");

                // 设置打开命令

                // 执行注册表添加命令（注意/d参数后直接跟命令字符串，不加额外引号）
                executeRegCommand("add", protocolKey + "\\shell\\open\\command", "/ve", "/d", command, "/f");
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 执行reg命令
     */
    private static void executeRegCommand(String... args) throws IOException, InterruptedException {
        String[] command = new String[args.length + 1];
        command[0] = "reg";
        System.arraycopy(args, 0, command, 1, args.length);

        Process process = new ProcessBuilder(command)
                .redirectErrorStream(true)
                .start();

        // 读取命令输出
        String output = new BufferedReader(new InputStreamReader(process.getInputStream()))
                .lines().collect(Collectors.joining("\n"));
        int exitCode = process.waitFor();

        if (exitCode != 0) {
            logger.error("Registry command failed: {}", String.join(" ", command));
            logger.error("Output: {}", output);
            throw new RuntimeException("注册表操作失败: " + String.join(" ", args) + "\nOutput: " + output);
        }
    }

    /**
     * 检查系统协议（http/https/magnet）是否已注册
     * 
     * @return true如果所有协议均已注册，false otherwise
     */
    public static boolean areSystemProtocolsRegistered() {
        // 检查所有协议是否都已注册
        for (String protocol : PROTOCOLS) {
            if (!isProtocolRegistered(protocol)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 检查单个协议是否已注册
     * 
     * @param protocol 协议名称（如http、magnet）
     * @return true如果已注册，false otherwise
     */
    private static boolean isProtocolRegistered(String protocol) {
        try {
            String protocolKey = "HKEY_CURRENT_USER\\Software\\Classes\\" + protocol;
            // 查询协议命令配置
            Process process = new ProcessBuilder("reg", "query", protocolKey + "\\shell\\open\\command", "/ve")
                    .redirectErrorStream(true)
                    .start();
            String output = new BufferedReader(new InputStreamReader(process.getInputStream()))
                    .lines().collect(Collectors.joining("\n"));
            int exitCode = process.waitFor();

            logger.info("协议{}注册状态: {}", protocol, (exitCode == 0 ? "已注册" : "未注册"));
            logger.info("注册表命令输出: {}", output);

            return true;
        } catch (IOException | InterruptedException e) {
            logger.error("协议{}检查失败: {}", protocol, e.getMessage());
            return false;
        }
    }
}